package com.hitalkie.teacher.activity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.adapter.LessonHintRvAdapter;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.model.Lesson;
import com.hitalkie.teacher.model.TopicHint;
import com.hitalkie.teacher.util.OkHttpManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Locale;

/**
 * Created by charliema on 04/03/2017.
 */
public class LessonHintListActivity extends BaseActivity {

    public static final String EXTRA_LESSON = "com.hitalkie.talkie.extra.LESSON";

    private Lesson mLesson;

    private TextToSpeech tts = null;
    private MediaPlayer mp = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTts();
        initView();
        initData();
        getLessonDetail(mLesson);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tts != null) {
            tts.shutdown();
        }
        if (mp != null) {
            mp.release();
        }
    }

    private void initTts() {
        tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int status) {
                // 如果装载TTS引擎成功
                if (status == TextToSpeech.SUCCESS) {
                    // 设置使用美式英语朗读
                    int result = tts.setLanguage(Locale.US);
                    // 如果不支持所设置的语言
                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
                        Toast.makeText(getActivity(), "TTS暂时不支持这种语言的朗读！", Toast.LENGTH_LONG).show(); // TODO language
                    }
                }
            }
        });
    }

    private void initView() {
        setContentView(R.layout.view_lesson_hint_list);
        initTitleBar();
        initSrl();
        initRv();
    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    private void initData() {
        mLesson = (Lesson) getIntent().getSerializableExtra(EXTRA_LESSON);
    }

    private void initSrl() {
        SwipeRefreshLayout srl = (SwipeRefreshLayout) findViewById(R.id.srl);
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getLessonDetail(mLesson);
            }
        });
    }

    private void initRv() {
        RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setAdapter(new LessonHintRvAdapter());
        ((LessonHintRvAdapter) rv.getAdapter()).setOnItemClickListener(new LessonHintRvAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(TopicHint data) {

            }

            @Override
            public void onSample(TopicHint data) {

            }

            @Override
            public void onNote(TopicHint data) {

            }
        });
    }

    private void updateView() {
        RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
        ((LessonHintRvAdapter) rv.getAdapter()).setData(mLesson.topic.topic_hints);

    }

    private void getLessonDetail(Lesson lesson) {
        if (lesson == null) {
            return;
        }
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        Request.Builder reqBuilder = new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_LESSON + lesson.id);
        OkHttpManager.client.newCall(reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        try {
                            final LessonDetailResp resp = new Gson().fromJson(jsonStr, LessonDetailResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        mLesson = resp.lesson;
                                        updateView();
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            response.body().close();
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                                }
                            });
                        }
                    }
                });
    }

    private static class LessonDetailResp extends BaseResponse {
        Lesson lesson;
    }
}
